<?php

declare(strict_types=1);

namespace App\Logic\User\Service\Ai;

use App\Constant\CacheKey;
use App\Library\HttpClient;
use App\Library\RedisClient;
use App\Logic\User\Service\BaseService;
use App\Logic\User\Service\User\UserScoreHistoryService;
use App\Logic\User\Service\UserServiceInterface;
use Closure;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Storage;

/**
 * 视频解析
 */
class VideoService extends BaseService implements UserServiceInterface
{

    public static function searchWhere(array $requestParams): Closure
    {
        return function () {
        };
    }

    public function serviceSelect(array $requestParams): array
    {
        return [];
    }

    public function serviceCreate(array $requestParams): array
    {
        if (!RedisClient::client()->set(CacheKey::$aiLimit . $this->getUserUid(), 1, ["nx", "ex" => 5])) {
            $createResult["msg"] = "请求过快";
            return $createResult;
        }
        $createResult = [
            "code" => 2,
            "msg"  => "解析失败",
        ];
        $createScoreHistory = (new UserScoreHistoryService())->serviceCreate([
            "score" => 200,
            "title" => "视频解析",
            "type"  => 2,
        ]);
        if ($createScoreHistory["code"] == 1) {
            try {
                $pattern = "/(https?:\/\/[^\s]+)/";
                preg_match_all($pattern, $requestParams["url"], $matches);
                if (!empty($matches[0])) {
                    $httpClientResult = HttpClient::client()->get("https://hmily.vip/api/jx/?key=6BA9C7B78C2F353D&url=" . $matches[0][0]);
                    $content = $httpClientResult->getBody()->getContents();
                    $contentArray = json_decode($content, true);
                    if ($contentArray["code"] == 200) {
                        // 处理视频
                        $disk = Storage::disk('public_disk');
                        $videoName = md5(time() . rand()) . '.mp4';
                        $disk->put($videoName, file_get_contents($contentArray["video_url"]));
                        // 处理音频
                        $audioName = md5(time() . rand()) . '.mp3';
                        $disk->put($audioName, file_get_contents($contentArray["audio_url"]));
                        return [
                            "code"       => 0,
                            "cover_url"  => $contentArray["cover_url"],
                            "video_url"  => env("APP_URL") . $videoName,
                            "msg"        => "解析成功",
                            "audio_url"  => env("APP_URL") . $audioName,
                            "duration"   => $contentArray["duration"],
                            "title"      => $contentArray["title"],
                            "time"       => $contentArray["time"],
                            "audio_name" => $audioName,
                        ];
                    }
                }
                $createResult["msg"] = "视频解析失败";
            } catch (GuzzleException $e) {
                $createResult["msg"] = $e->getMessage();
            }
        } else {
            $createResult["msg"] = "积分处理失败";
        }
        return $createResult;
    }

    public function serviceUpdate(array $requestParams): array
    {
        return [];
    }

    public function serviceDelete(array $requestParams): int
    {
        return 0;
    }

    public function serviceFind(array $requestParams): array
    {
        return [];
    }
}
